#include <string.h>
#include <assert.h>

namespace wangshu
{   
    template<class T>
    class vector
    {
    public:
        typedef T* iterator;
        typedef const T* const_iterator;
        
        vector(): _start(nullptr), _finish(nullptr), _endofStorage(nullptr)
        {}
        
        ~vector()
        {
            delete [] _start;
            _start = _finish = _endofStorage = nullptr;
        }

        template<class Inputiterator>
        vector(Inputiterator first, Inputiterator last)
        {
            while(first != last)
            {
                push_back(*first);
                first++;
            }
        }
        
        vector(size_t n, const T& val = T())
        {

        }

        void reserve(size_t n)
        {
            if(n > capacity())
            {
                size_t sz = size();
                T* tmp = new T(n);
                if(_start)
                {
                    // 不应该用memcpy(浅拷贝)，释放空间时重复释放同一块空间会出问题
                    for(int i = 0; i < sz; i++)
                    {
                        tmp[i] = _start[i];
                    }
                    delete [] _start;
                }
                
                _start = tmp;
                _finish = _start + sz;
                _endofStorage = _start + n;
            }
        }
        
        void push_back(T val)
        {
            size_t cp = capacity(), sz = size();
            if(_finish == _endofStorage)
            {
                reserve(cp == 0 ? 4 : 2 * cp);
            }
            *_finish = val;
            _finish++;
        }
        T operator[](size_t pos)
        {
            assert(pos < size());
            return _start[pos];
        }
        size_t size() const
        {
            return _finish - _start;
        }
        size_t capacity() const
        {
            return _endofStorage - _start;
        }

        iterator begin()
        {
            return _start;
        }
        iterator end()
        {
            return _finish;
        }
    private:
        iterator _start;
        iterator _finish;
        iterator _endofStorage;
    };
}